﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using MyGeneration.dOOdads;
using MethodIT.Helper;

using Hr20.DAL;
using Hr20.BLL;
using Hr20.ProcessFlow;

namespace Appraisal.Web.ZB
{
    public partial class ZbFromItemCheck : System.Web.UI.Page
    {
        private const string HTML_SPACE = "&nbsp;";
        private const string ITEM_CTRL_PREID = "KPItem_";

        protected void Page_Load(object sender, EventArgs e)
        {
            btnPrintTop.Attributes.Add("onclick", "excel(phTemplate);");
            btnPrintBottom.Attributes.Add("onclick", "excel(phTemplate);");

            int nSubID = HelperURL.GetIntFromUrlString("SubID");
            int nKpID = HelperURL.GetIntFromUrlString("KpID");
            int nUmpID = HelperURL.GetIntFromUrlString("UmpID");
            int nDisplay = HelperURL.GetIntFromUrlString("Display");
            bool Display = nDisplay.Equals(1);

            DisplayRating(nSubID, nKpID, nUmpID, Display);
        }

        // 评分
        private void DisplayRating(int nSubID, int nKpID, int nUmpID, bool Display)
        {
            VW_ZB_ItemResult itemResult = new VW_ZB_ItemResult();
            itemResult.Where.KpID.Value = nKpID;
            itemResult.Where.UmpID.Value = nUmpID;
            itemResult.Where.SubID.Value = nSubID;
            itemResult.Query.Load();

            KP_Subject subject = new KP_Subject();
            subject.LoadByPrimaryKey(itemResult.SubID);
            labKpName.Text = itemResult.KpName;
            labSubName.Text = itemResult.SubName;
            labBidderName.Text = subject.Bidder;
            labEndTime.Text = subject.EndDate.ToString();
            labUmpName.Text = itemResult.UmpName;

            lbtnSubmit.Enabled = !Display;
            lbtnSubmitBottom.Enabled = !Display;

            phTemplate.Controls.Add(CreateTable(itemResult, false));

            lbtnSubmit.Attributes.Add(ConstantController.MSG_ALERT_ACTION, ConstantController.MSG_ALERT_SUBMIT_SCRIPT);
            lbtnSubmitBottom.Attributes.Add(ConstantController.MSG_ALERT_ACTION, ConstantController.MSG_ALERT_SUBMIT_SCRIPT);
        }

        private Table CreateTable(VW_ZB_ItemResult vwResult, bool IsShow)
        {

            KP_Subject_Employee se = new KP_Subject_Employee();
            ZB_Tender tender = new ZB_Tender();
            string TenderName = "";

            se.Load(vwResult.SubID);
            int nTenderCount = se.RowCount;
            int TableWidth = 700 + nTenderCount * 50;

            //创建表头
            Table tb = new Table();
            TableRow tr = new TableRow();
            TableCell tc = new TableCell();

            //tb.Attributes.Add("style", zTable.TableStyle);
            tb.Attributes.Add("border", "1");
            //tb.Attributes.Add("class", "ms-formlabel");
            tb.Attributes.Add("width", TableWidth + "px");
            tb.Attributes.Add("cellpadding", "0");
            tb.Attributes.Add("cellspacing", "0");
            tb.ID = "dtable";

            KP_Subject_Table_Ump su = new KP_Subject_Table_Ump();
            su.Where.SubjectID.Value = vwResult.SubID;
            //若是参考项目，则现示所有评分表
            if (!IsShow) su.Where.UmpID.Value = vwResult.UmpID;
            su.Where.UmpType.Value = 0;//评分
            su.Where.KpTableID.Value = vwResult.KpID;
            su.Query.Load();
            int nUmpCount = su.RowCount;

            KP_Master kpTable = new KP_Master();
            kpTable.LoadByPrimaryKey(vwResult.KpID);

            tr = new TableRow();
            tc = HelperTable.CreateStyleCell(1, 3 + nTenderCount, kpTable.Title, "font-size: 18.0pt;font-weight: 700;font-style: normal;text-decoration: none;font-family: 黑体;text-align: center;vertical-align: middle;white-space: normal;");
            tr.Cells.Add(tc);
            tb.Rows.Add(tr);

            //加入项目信息
            tr = new TableRow();
            KP_Subject subject = new KP_Subject();
            subject.LoadByPrimaryKey(vwResult.SubID);
            int nCol1 = (3 + nTenderCount) / 2;
            int nCol2 = (3 + nTenderCount) - nCol1;
            tr.Cells.Add(HelperTable.CreateStyleCell(1, nCol1, "项目名称：" + subject.SubjectName, HelperTable.ALIGN_LEFT));
            tr.Cells.Add(HelperTable.CreateStyleCell(1, nCol2, "项目编号：" + subject.Code, HelperTable.ALIGN_RIGHT));
            tb.Rows.Add(tr);

            tr = new TableRow();
            tr.Cells.Add(HelperTable.CreateStyleCell(1, nCol1, "评标时间：" + DateTime.Now.ToString(), HelperTable.ALIGN_LEFT));
            tr.Cells.Add(HelperTable.CreateStyleCell(1, nCol2, "评标地点：" + subject.Address, HelperTable.ALIGN_RIGHT));
            tb.Rows.Add(tr);

            tr = new TableRow();
            tr.Cells.Add(HelperTable.CreateCell(2, 1, "评审标准"));
            tr.Cells.Add(HelperTable.CreateCell(2, 1, "评审因素"));
            tr.Cells.Add(HelperTable.CreateCell(2, 1, "评审标准"));
            tr.Cells.Add(HelperTable.CreateCell(1, nTenderCount, "记录评审结果"));
            tb.Rows.Add(tr);

            //表头投标公司
            tr = new TableRow();
            se.Rewind();
            while (!se.EOF)
            {
                tender.LoadByPrimaryKey(se.EmployeeID);
                TenderName = tender.Name;
                tr.Cells.Add(HelperTable.CreateCell(1, 1, TenderName));

                se.MoveNext();
            }
            tb.Rows.Add(tr);


            KP_Template template = new KP_Template();
            template = new KP_Template();
            template.Where.KP_ID.Value = vwResult.KpID;
            template.Where.Is_Group.Value = 1;
            template.Query.Load();
            //int nGroupCount = template.RowCount;

            //添加指标集
            tr = new TableRow();
            while (!template.EOF)
            {
                KP_Template itemTemplate = new KP_Template();
                itemTemplate.Where.Parent_Item_ID.Value = template.Item_ID;
                itemTemplate.Query.Load();
                tc = HelperTable.CreateCell(itemTemplate.RowCount, 1);
                tc.Controls.Add(new LiteralControl(template.Item_Name));
                if (!IsShow)
                {
                    se.Rewind();
                    while (!se.EOF)
                    {
                        CreateScoreItem(vwResult, su.UmpID, template.Item_ID, se.EmployeeID, tc);
                        se.MoveNext();
                    }
                }
                tr.Cells.Add(tc);

                //添加指标项目
                while (!itemTemplate.EOF)
                {
                    tr.Cells.Add(HelperTable.CreateCell(1, 1, itemTemplate.Item_Name));
                    //指标项评分描述
                    tc = HelperTable.CreateCell(1, 1, itemTemplate.Item_Desc);
                    tr.Cells.Add(tc);

                    se.Rewind();
                    while (!se.EOF)
                    {
                        DataRow[] items = vwResult.DefaultView.Table.Select("UmpID=" + su.UmpID + " and ItemID= " + itemTemplate.Item_ID + " and TenderID=" + se.EmployeeID);
                        string sScore = items[0][VW_ZB_ItemResult.ColumnNames.ItemScore].ToString();
                        string sText = items[0][VW_ZB_ItemResult.ColumnNames.ItemText].ToString();
                        tc = HelperTable.CreateCell(1, 1, "");

                        if (!IsShow)
                        {
                            CreateScoreItem(vwResult, su.UmpID, itemTemplate.Item_ID, se.EmployeeID, tc);
                        }
                        else
                        {
                            tc.Text = GetItemScore(itemTemplate.Item_Type.ToString(), sScore, sText);
                        }
                        tr.Cells.Add(tc);

                        se.MoveNext();
                    }

                    tb.Rows.Add(tr);
                    tr = new TableRow();

                    itemTemplate.MoveNext();
                }

                template.MoveNext();
            }

            //表脚
            tr = new TableRow();
            tr.Cells.Add(HelperTable.CreateStyleCell(1, 3 + nTenderCount, "  注：投标文件的任何一项因素不符合评审标准均构成废标，不能进入详细评审。", HelperTable.ALIGN_LEFT));
            tb.Rows.Add(tr);

            tr = new TableRow();
            tr.Cells.Add(HelperTable.CreateStyleCell(1, 3 + nTenderCount, "评标委员会成员签字确认：", HelperTable.ALIGN_LEFT));
            tb.Rows.Add(tr);

            tr = new TableRow();
            tr.Cells.Add(HelperTable.CreateStyleCell(1, 3 + nTenderCount, "监标人：", HelperTable.ALIGN_LEFT));
            tb.Rows.Add(tr);

            //se.Rewind();
            //while (!se.EOF)
            //{
            //    DataRow[] items = vwResult.DefaultView.Table.Select("UmpID=" + su.UmpID + " and TenderID=" + se.EmployeeID);
            //    string sScore = items[0][VW_ZB_ItemResult.ColumnNames.EntryScore].ToString();
            //    tc = HelperTable.CreateCell(1, 1, sScore);
            //    if (!IsShow)
            //    {
            //        CreateTotalItem(vwResult, su.UmpID, se.EmployeeID, tc);
            //    }
            //    else
            //    {
            //        tc.Text = sScore;
            //    }

            //    tr.Cells.Add(tc);
            //    se.MoveNext();
            //}

            //一个评分表创建完成;

            tr = new TableRow();
            tr.Cells.Add(HelperTable.CreateStyleCell(1, 3 + nTenderCount, "湖北信通通信有限公司惠达招标分公司", HelperTable.ALIGN_RIGHT));
            tb.Rows.Add(tr);

            return tb;

        }

        private void CreateScoreItem(VW_ZB_ItemResult vwResult, int UmpID, int ItemID, int TenderID, TableCell tc)
        {
            TextBox txtItem = new TextBox();
            DataRow[] items = vwResult.DefaultView.Table.Select("UmpID=" + UmpID + " and TenderID=" + TenderID + " and itemID=" + ItemID);
            string sScore = items[0][VW_ZB_ItemResult.ColumnNames.ItemScore].ToString();
            string sText = items[0][VW_ZB_ItemResult.ColumnNames.ItemText].ToString();
            string sItemName = items[0][VW_ZB_ItemResult.ColumnNames.ItemName].ToString();
            int ItemWidth = HelperDigit.ConvertToInt32(items[0][VW_ZB_ItemResult.ColumnNames.Item_Width].ToString());
            string sType = items[0][VW_ZB_ItemResult.ColumnNames.Item_Type].ToString();

            txtItem.ID = ITEM_CTRL_PREID + ItemID.ToString() + "_" + TenderID.ToString();
            txtItem.ToolTip = TenderID.ToString();
            txtItem.Width = Unit.Pixel(ItemWidth);
            txtItem.Text = GetItemScore(sType, sScore, sText);
            if (sType.Equals("1"))
            {
                txtItem.TextMode = TextBoxMode.MultiLine;
                txtItem.Height = Unit.Pixel(54);
            }
            else
            {
                string sMessage = String.Format("popHint(this, '{0}');", sText);
                txtItem.Attributes.Add("onfocus", sMessage);
            }

            tc.Controls.Add(txtItem);

            // 添加评分有效性验证控件
            RequiredFieldValidator validator = new RequiredFieldValidator();
            validator.ID = "RFV_" + ITEM_CTRL_PREID + ItemID.ToString() + "_" + TenderID.ToString();
            validator.ControlToValidate = ITEM_CTRL_PREID + ItemID.ToString() + "_" + TenderID.ToString();
            //validator.ClientValidationFunction = "is_valid_score";
            validator.ErrorMessage = "请评分项－" + sItemName;
            validator.Text = "*";
            validator.Display = ValidatorDisplay.Dynamic;
            tc.Controls.Add(validator);

            //添加数值型或字符型验证
            //0为数值型验证
            if (sType.Equals("0"))
            {
                RegularExpressionValidator rev = new RegularExpressionValidator();
                rev.ID = "REV_" + ITEM_CTRL_PREID + ItemID.ToString() + "_" + TenderID.ToString();
                rev.ControlToValidate = ITEM_CTRL_PREID + ItemID.ToString() + "_" + TenderID.ToString();
                //rev.ClientValidationFunction = "is_valid_score";
                rev.ValidationExpression = @"^\d+(\.\d+)?$";
                rev.ErrorMessage = "请填写一个数值－" + sItemName;
                rev.Text = "*";
                rev.Display = ValidatorDisplay.Dynamic;
                tc.Controls.Add(rev);
            }
        }

        //选择是数字还是文本
        private string GetItemScore(string sType, string sScore, string sText)
        {
            string sStr = "";
            if (sType.Equals("0"))
            {
                sStr = sScore;
            }
            else
            {
                sStr = sText;
            }

            return sStr;
        }

        private void CreateTotalItem(VW_ZB_ItemResult vwResult, int UmpID, int TenderID, TableCell tc)
        {
            Label lbItemScore = new Label();
            DataRow[] items = vwResult.DefaultView.Table.Select("UmpID=" + UmpID + " and TenderID=" + TenderID);
            string sScore = items[0][VW_ZB_ItemResult.ColumnNames.EntryScore].ToString();

            lbItemScore.ID = "lb_" + ITEM_CTRL_PREID + TenderID.ToString();
            lbItemScore.Text = sScore;
            tc.Controls.Add(lbItemScore);

        }

        // 检验合法性
        private void CheckValid()
        {
            //不能全是10也不能全是1
            bool bIsAll_10 = true;
            bool bIsAll_1 = true;
            bool bIsBetween = true;
            decimal Score = 0;
            //double MaxScore = 0;
            //double MinScore = 0;

            int ItemID = 0;
            KP_Template temp = new KP_Template();

            for (int i = 0; i < Request.Form.Count; i++)
            {
                string sKeyName = Request.Form.GetKey(i);
                if (sKeyName.IndexOf(ITEM_CTRL_PREID) >= 0)
                {
                    sKeyName = sKeyName.Replace(ITEM_CTRL_PREID, "");
                    sKeyName = sKeyName.Split('_')[0];
                    ItemID = HelperDigit.ConvertToInt32(sKeyName);
                    temp.LoadByPrimaryKey(ItemID);
                    //若是数值数据则计算总分
                    if ((Request.Form[i] != null) && (temp.Item_Type == 0))
                    {
                        decimal dCurrentItemScore = HelperCurrency.GetCurrencyDecimal(Request.Form[i]);
                        bIsAll_10 = (bIsAll_10 && dCurrentItemScore == temp.Max_Score);
                        bIsAll_1 = (bIsAll_1 && dCurrentItemScore == temp.Min_Score);

                        bIsBetween = (bIsBetween) && (dCurrentItemScore >= temp.Min_Score) && (dCurrentItemScore <= temp.Max_Score);
                        //MaxScore += (double)temp.Max_Score;
                        //MinScore += (double)temp.Min_Score;
                        //计算总分
                        Score += dCurrentItemScore;
                    }
                }
            }
            //判断不能是满分、不能是最低分、不能超出分值区间
            //vld_Template.IsValid = (!bIsAll_10) && (!bIsAll_1) && (bIsBetween);
            vld_Template.IsValid = bIsBetween;

            //控制评分表最高分、最低分
            //int nEntryID = HelperURL.GetIntFromUrlString("EntryID");
            //VIEW_KP_ENTRY vw = new VIEW_KP_ENTRY();
            //vw.Where.Entry_ID.Value = nEntryID;
            //if (vw.Query.Load())
            //{
            //    KP_Subject_Table st = new KP_Subject_Table();
            //    if (st.LoadByPrimaryKey(vw.SubjectID, vw.KP_ID))
            //    {
            //        vld_100.IsValid = ((Score >= st.MinScore) && (Score <= st.MaxScore));
            //    }
            //}

        }

        // 保存结果，bIsSaved = false, 仅计算结果，不保存
        private void DoSave(bool bIsSaved)
        {
            //数据验证
            CheckValid();

            if (!Page.IsValid)
                return;

            Count();

            if (bIsSaved)
            {
                Save();
                HelperMessage.Message("保存成功");
            }
        }

        private void Save()
        {
            int nSubID = HelperURL.GetIntFromUrlString("SubID");
            int nKpID = HelperURL.GetIntFromUrlString("KpID");
            int nUmpID = HelperURL.GetIntFromUrlString("UmpID");

            VW_ZB_ItemResult vw = new VW_ZB_ItemResult();
            vw.Where.KpID.Value = nKpID;
            vw.Where.SubID.Value = nSubID;
            vw.Where.UmpID.Value = nUmpID;
            vw.Query.Load();
            while (!vw.EOF)
            {
                KP_Item_Result ir = new KP_Item_Result();
                ir.LoadByPrimaryKey(vw.ResultID);

                string ctrlID = ITEM_CTRL_PREID + vw.ItemID.ToString() + "_" + vw.TenderID;
                Control ctrl = phTemplate.FindControl(ctrlID);
                if (ctrl != null)
                {
                    TextBox tb = (TextBox)ctrl;
                    if (vw.Item_Type.Equals(0))
                    {
                        ir.Item_Score = HelperCurrency.GetCurrencyDecimal(tb.Text);
                    }
                    else
                    {
                        ir.Item_Text = tb.Text;
                    }
                    ir.Save();
                }

                vw.MoveNext();
            }
            KP_Subject_Employee se = new KP_Subject_Employee();
            se.Where.SID.Value = nSubID;
            se.Query.Load();
            while (!se.EOF)
            {
                DataRow[] items = vw.DefaultView.Table.Select("TenderID=" + se.EmployeeID);
                string sEntryID = items[0][VW_ZB_ItemResult.ColumnNames.EntryID].ToString();
                KP_Entry entry = new KP_Entry();
                if (entry.LoadByPrimaryKey(HelperDigit.ConvertToInt32(sEntryID)))
                {
                    Control ctrlTotal = phTemplate.FindControl("lb_" + ITEM_CTRL_PREID + se.EmployeeID.ToString());
                    if (ctrlTotal != null)
                    {
                        Label lb = (Label)ctrlTotal;
                        entry.Score = HelperCurrency.GetCurrencyDecimal(lb.Text);

                    }
                }
                entry.Save();

                se.MoveNext();
            }
            //修改评分专家填报状态
            KP_Subject_Table_Ump stu = new KP_Subject_Table_Ump();
            stu.Where.SubjectID.Value = nSubID;
            stu.Where.KpTableID.Value = nKpID;
            stu.Where.UmpID.Value = nUmpID;
            stu.Where.UmpType.Value = 0;
            stu.Query.Load();
            stu.Status = 1;
            stu.Save();
        }

        //计算分数
        private void Count()
        {
            int nSubID = HelperURL.GetIntFromUrlString("SubID");
            int nKpID = HelperURL.GetIntFromUrlString("KpID");
            int nUmpID = HelperURL.GetIntFromUrlString("UmpID");

            KP_Item_Result kpItemResult = new KP_Item_Result();
            KP_Template template = new KP_Template();
            VW_ZB_ItemResult vw = new VW_ZB_ItemResult();
            KP_Subject_Employee se = new KP_Subject_Employee();
            decimal dTotal = 0;

            se.Where.SID.Value = nSubID;
            se.Query.Load();
            //第一层投标人
            while (!se.EOF)
            {
                vw = new VW_ZB_ItemResult();
                vw.Where.KpID.Value = nKpID;
                vw.Where.Is_Group.Value = true;
                vw.Where.SubID.Value = nSubID;
                vw.Where.UmpID.Value = nUmpID;
                vw.Where.TenderID.Value = se.EmployeeID;
                vw.Query.Load();
                //第二层指标集
                while (!vw.EOF)
                {
                    VW_ZB_ItemResult vwItem = new VW_ZB_ItemResult();
                    decimal dGroupTotal = 0;

                    vwItem.Where.KpID.Value = nKpID;
                    vwItem.Where.Is_Group.Value = false;
                    vwItem.Where.SubID.Value = nSubID;
                    vwItem.Where.UmpID.Value = nUmpID;
                    vwItem.Where.ParentID.Value = vw.ItemID;
                    vwItem.Where.TenderID.Value = se.EmployeeID;
                    vwItem.Query.Load();

                    //第三层指标项目
                    while (!vwItem.EOF)
                    {
                        string ctrlID = ITEM_CTRL_PREID + vwItem.ItemID.ToString() + "_" + se.EmployeeID.ToString();
                        Control ctrl = phTemplate.FindControl(ctrlID);
                        if (ctrl != null)
                        {
                            TextBox tb = (TextBox)ctrl;
                            string sResult = tb.Text;
                            decimal d = 0;
                            if (vwItem.Item_Type.Equals(0))
                            {
                                d = HelperCurrency.GetCurrencyDecimal(sResult);
                            }
                            dGroupTotal += d * vwItem.Item_Quotiety;
                        }

                        vwItem.MoveNext();
                    }
                    string ctrlTotalID = ITEM_CTRL_PREID + vw.ItemID.ToString() + "_" + se.EmployeeID.ToString();
                    Control ctrlTotal = phTemplate.FindControl(ctrlTotalID);
                    if (ctrlTotal != null)
                    {
                        TextBox tbTotal = (TextBox)ctrlTotal;
                        tbTotal.Text = dGroupTotal.ToString();
                    }
                    dTotal += dGroupTotal * vw.Item_Quotiety;

                    vw.MoveNext();
                }
                string lbID = "lb_" + ITEM_CTRL_PREID + se.EmployeeID.ToString();
                Control ctrlLable = phTemplate.FindControl(lbID);
                if (ctrlLable != null)
                {
                    Label lb = (Label)ctrlLable;
                    lb.Text = dTotal.ToString("N2");
                }
                dTotal = 0;

                se.MoveNext();
            }
        }


        private void ShowScore(string nItemID, decimal dScore, bool IsLabel)
        {
            //Control ctrl = phTemplate.FindControl("lb_" + ITEM_CTRL_PREID + nItemID.ToString());
            Control ctrl = phTemplate.FindControl(nItemID);
            if (ctrl != null)
            {
                if (IsLabel)
                {
                    Label lbItemScore = (Label)ctrl;
                    lbItemScore.Text = dScore.ToString("N2");
                }
                else
                {
                    TextBox txtItem = (TextBox)ctrl;
                    txtItem.Text = dScore.ToString("N2");
                }
            }
        }


        protected void lbtnSubmit_Click(object sender, System.EventArgs e)
        {
            DoSave(true);
        }

        protected void lbtnSubmitBottom_Click(object sender, System.EventArgs e)
        {
            DoSave(true);
        }

        protected void lbtnCompute_Click(object sender, System.EventArgs e)
        {
            DoSave(false);
        }

        protected void lbtnComputeBottom_Click(object sender, System.EventArgs e)
        {
            DoSave(false);
        }
    }
}
